//
//  CHSUpgradeComponent.m
//  MerchantBusinessClient
//
//  Created by 海参 on 2021/7/19.
//  Copyright © 2021 com.Chs. All rights reserved.
//

#import "CAIUpgradeManager.h"
#import "CAIUpgradeTool.h"
#import "CAIUpgradeAlert.h"
#import <YYModel/YYModel.h>
#import <objc/message.h>
//#import <CAINetworkManager/NetworkManager.h>


@interface CAIUpgradeManager ()

@end


@implementation CAIUpgradeManager

static NSString *const kUpgrade_URL = @"/com.chs.app.mobileserver.update.inspect";


#pragma mark - UI


//已弃用
+ (void)checkUpdateWithUIWithNeedGreyAction:(void(^)(CAIClientVoModel *model,id responseObject))greyResult
                                 configueUI:(nullable CAIUpgradeGeneralUIConfig *)config
                               failureBlock:(nullable void(^)(id _Nonnull meta))failureBlock
{
    [self checkUpdateDetailWithResult:nil needStoreUpgrade:^(CAIClientVoModel * _Nonnull model) {
        [self showStoreUpgradeAlertWithModel:model configue:config];
        
    } needGrey:^(CAIClientVoModel * _Nonnull model, id  _Nonnull responseObject) {
        ///是否需要灰度，未登录为NO,登录且命中灰度为YES，则跳转testFlight
        [self showGreyAlertWithModel:model config:config response:responseObject grey:^(CAIClientVoModel *model, NSString *middleUrl, NSString *responseObject) {
            if (greyResult) {
                greyResult(model,responseObject);
            }
        }];
    } failureBlock:failureBlock];
}


/// 请求业务接口基础检查版本是否有更新,不带UI弹窗；(灰度||(应用市场升级||ABM))
/// @param checkResult isHaveNewVersion：是否有新版本更新，包含灰度和应用市场升级
/// @param failureBlock 请求失败回调
+ (void)checkUpdateGeneralWithResult:(nullable void(^)(CHSClientPackageModel *model,BOOL isHaveNewVersion))checkResult
                        failureBlock:(nullable void(^)(id meta))failureBlock
{
    [self requestCheckVersionUpdateSuccess:^(CHSClientPackageModel *packageModel) {
        [CAIUpgradeManager performResultBlockWithModel:packageModel result:checkResult];
    } failureBlock:failureBlock];
}


/// 详细请求业务接口详细检查版本是否有更新,不带UI弹窗，有灰度、(应用市场升级||ABM)的独立回调；
/// @param checkResult 是否有新版本更新，包含灰度和应用市场升级;
/// @param storeResult 有应用市场版本升级回调;model:请求response模型；
/// @param greyResult 有灰度的回调；model:请求response模型;responseObject:源json数据字符串
/// @param failureBlock 请求失败回调
+ (void)checkUpdateDetailWithResult:(nullable void(^)(BOOL isHaveNewVersion))checkResult
                   needStoreUpgrade:(nullable void(^)(CAIClientVoModel *model))storeResult
                           needGrey:(nullable void(^)(CAIClientVoModel *model,id responseObject))greyResult
                       failureBlock:(nullable void(^)(id meta))failureBlock
{
    [self checkUpdateGeneralWithResult:^(CHSClientPackageModel * _Nonnull packagModel, BOOL isHaveNewVersion) {
        if (checkResult) {
            checkResult(isHaveNewVersion);
        }
        if (isHaveNewVersion) {
            CAIClientVoModel *model = packagModel.voModel;
            if (model.isGrey) {
                if (greyResult) {
                    greyResult(model,packagModel.responseObject);
                }
            }else{
                if (storeResult) {
                    storeResult(model);
                }
            }
        }
    } failureBlock:failureBlock];
}


#pragma mark -自带UI弹窗的检查

+ (void)checkUpdateWithUIWithResult:(nullable void(^)(BOOL isHaveNewVersion))checkResult
           needGreyMiddlePageAction:(void(^)(CAIClientVoModel *model,NSString *middleUrl,id responseObject))greyMiddleActionResult
                       failureBlock:(nullable void(^)(id meta))failureBlock
{
    [self checkUpdateWithUIWithConfigueUI:nil
                                   result:checkResult
                 needGreyMiddlePageAction:greyMiddleActionResult
                             failureBlock:failureBlock];
}

+ (void)checkUpdateWithUIWithConfigueUI:(nullable CAIUpgradeGeneralUIConfig *)config
                                 result:(nullable void(^)(BOOL isHaveNewVersion))checkResult
               needGreyMiddlePageAction:(void(^)(CAIClientVoModel *model,NSString *middleUrl,id responseObject))greyMiddleActionResult
                           failureBlock:(nullable void(^)(id meta))failureBlock
{
    [self checkUpdateDetailWithResult:checkResult
                     needStoreUpgrade:^(CAIClientVoModel * _Nonnull model) {
        [CAIUpgradeManager showStoreUpgradeAlertWithModel:model configue:config];
    } needGrey:^(CAIClientVoModel * _Nonnull model, id  _Nonnull responseObject) {
        [CAIUpgradeManager showGreyAlertWithModel:model config:config response:responseObject grey:greyMiddleActionResult];
    } failureBlock:failureBlock];
}




#pragma mark - 根据外部传入模型判断

+ (void)checkUpdateWithModel:(CAIClientVoModel *)model
                      result:(nullable void(^)(CHSClientPackageModel *packageModel,BOOL isHaveNewVersion))checkResult
{
    NSString *jsonStr = [model yy_modelToJSONString];
    CHSClientPackageModel *packageModel = [[CHSClientPackageModel alloc] init];
    packageModel.voModel = model;
    packageModel.responseObject = jsonStr;
    [CAIUpgradeManager performResultBlockWithModel:packageModel result:checkResult];
}

+ (void)checkUpdateWithUIWithModel:(CAIClientVoModel *)model
                        configueUI:(nullable CAIUpgradeGeneralUIConfig *)config
                            result:(nullable void(^)(BOOL isHaveNewVersion))checkResult
          needGreyMiddlePageAction:(void(^)(CAIClientVoModel *model,NSString *middleUrl,id responseObject))greyMiddleActionResult
{
    [self checkUpdateWithModel:model result:^(CHSClientPackageModel * _Nonnull packageModel, BOOL isHaveNewVersion) {
        if (checkResult) {
            checkResult(isHaveNewVersion);
        }
        if (isHaveNewVersion) {
            CAIClientVoModel *model = packageModel.voModel;
            if (model.isGrey) {
                NSString *response = [model yy_modelToJSONString];
                [CAIUpgradeManager showGreyAlertWithModel:model config:config response:response grey:greyMiddleActionResult];
            }else{
                [CAIUpgradeManager showStoreUpgradeAlertWithModel:model configue:config];
            }
        }
    }];
}


+ (void)checkOnlyItunesWithUIWithModel:(CAIClientVoModel *)model
                           checkResult:(void(^)(BOOL isHaveNewVersion))checkResult
                               failure:(void(^)(NSError* error))failure{
    NSString *url;
    if (![NSString caiUpgradeIsEmpty:model.itunesCheckUrl]) {
        url = model.itunesCheckUrl;
    }else{
        url = [self appStoreAppInfomationURLForApplicationIdentifier:model.appId];
    }
    [ZXCheckAppItunesVersionManager checkAppStoreNewVersionWithUrl:url success:^(BOOL isHaveNewVersion, CAIItunesModel * _Nonnull itunesModel) {
        if (checkResult) {
            checkResult(isHaveNewVersion);
        }
        if (isHaveNewVersion) {
            model.versionNew = itunesModel.version;
            model.updateDescription = itunesModel.releaseNotes;
            [CAIUpgradeManager showStoreUpgradeAlertWithModel:model configue:nil];
        }
    } failure:^(NSError * _Nonnull error) {
        if (failure) {
            failure(error);
        }
    }];
}

#pragma mark - 请求检查结果处理

+ (void)performResultBlockWithModel:(CHSClientPackageModel *)packageModel
                             result:(nullable void(^)(CHSClientPackageModel *model,BOOL isHaveNewVersion))checkResult
{
    CAIClientVoModel *model = packageModel.voModel;
    if (model)
    {
        //是否有更新
        if (!model.isHaveNewVersion) {
            if (checkResult) {
                checkResult(packageModel,NO);
            }
            return;
        }
        
        if (model.isGrey || model.isABM) {
            if (checkResult) {
                checkResult(packageModel,YES);
            }
        }
        else
        {
            if (model.isItunesCheck) {
                ///如果没有配置，则使用兜底
                NSString *itunesCheckUrl;
                if (![NSString caiUpgradeIsEmpty:model.itunesCheckUrl]) {
                    itunesCheckUrl = model.itunesCheckUrl;
                }else{
                    itunesCheckUrl = [self appStoreAppInfomationURLForApplicationIdentifier:model.appId];
                }
                
                [ZXCheckAppItunesVersionManager checkAppStoreNewVersionWithUrl:itunesCheckUrl success:^(BOOL isHaveNewVersion, CAIItunesModel * _Nonnull itunesModel) {
                    if (checkResult) {
                        checkResult(packageModel,isHaveNewVersion);
                    }
                } failure:^(NSError * _Nonnull error) {
                    if (checkResult) {
                        checkResult(packageModel,YES);
                    }
                }];
            }else{
                if (checkResult) {
                    checkResult(packageModel,YES);
                }
            }
        }
    }
}

#pragma mark - 应用市场升级/APM 处理

+ (void)showStoreUpgradeAlertWithModel:(CAIClientVoModel * _Nonnull)model configue:(CAIUpgradeGeneralUIConfig *)config
{
    NSString *title = model.title;
    if (!model.title) {
        title = [NSString stringWithFormat:@"%@ %@",@"发现新版本", model.versionNew?model.versionNew:@""];
    }
    CAIUpgradeAlert *alert = [CAIUpgradeAlert showAlertWithImage:nil
                                                           title:title
                                                         content:model.updateDescription
                                                         isForce:model.isForceUpdate
                                                       nextBlock:^{
        if (model.isABM) {
            ((void(*)(id, SEL, NSString*, id))objc_msgSend)([self chsRouter],sel_registerName("routerWithUrl:params:"),model.codeRedemptionLink,nil);
        }else{
            NSString *url;
            if (![NSString caiUpgradeIsEmpty:model.appStoreUrl]) {
                url = model.appStoreUrl;
            }else{
                url = [self downLoadUrlWithAppId:model.appId];
            }
            [CAIUpgradeManager openURLToAppStoreForAppStoreUrl:url];
        }
    }];
    
    if (config) {
        alert.alertConfig = [self setAlertConfiguration:config];;
    }
}

#pragma mark - 灰度处理

+ (void)showGreyAlertWithModel:(CAIClientVoModel *_Nonnull)model
                        config:(CAIUpgradeGeneralUIConfig *)config
                      response:(NSString *)responseObject
                          grey:(void(^)(CAIClientVoModel *model,NSString *middleUrl,NSString *responseObject))greyResult
{
    ///是否需要灰度，未登录为NO,登录且命中灰度为YES，则跳转testFlight
    if (config.isGreyWithPresentAlert) {
        [self presentGreyAlertControllerWithModel:model configueUI:config greyAction:^{
            if (greyResult) {
                NSString *response = responseObject;
                if (!response)
                {
                    response = [model yy_modelToJSONString];
                }
                greyResult(model,model.middleUrl,response);
            }
        }];
    }else{
        [self showGreyAlertWithModel:model configueUI:config greyAction:^{
            if (greyResult) {
                NSString *response = responseObject;
                if (!response)
                {
                    response = [model yy_modelToJSONString];
                }
                greyResult(model,model.middleUrl,response);
            }
        }];
    }
}



#pragma mark -请求业务配置信息

/// 请求业务配置信息
/// @param success 成功回调
/// @param failureBlock failureBlock description
+ (void)requestCheckVersionUpdateSuccess:(void(^)(CHSClientPackageModel *model))success
                            failureBlock:(void(^)(id meta))failureBlock
{
    /*
     DataEntity * entity = [[DataEntity alloc] init];
     entity.urlString = kUpgrade_URL;
     [CHSNetworkManager requestPOSTWithEntity:entity
     responseModel:[CAIClientVoModel class]
     successBlock:^(CHSNetworkMetaModel * _Nonnull meta) {
     CAIClientVoModel *model = meta.data.model;
     if (success) {
     NSString *jsonStr = [CAIUpgradeTool getJSONSerializationStringFromJSONObject:meta.data.data];
     CHSClientPackageModel *packageModel = [[CHSClientPackageModel alloc] init];
     packageModel.voModel = model;
     packageModel.responseObject = jsonStr;
     success(packageModel);
     }
     } failureBlock:^(CHSNetworkMetaModel * _Nonnull meta) {
     if (failureBlock) {
     failureBlock(meta);
     }
     }];
     */
    NSLog(@"业务接口请求数据检查更新");
    if (failureBlock) {
        failureBlock(nil);
    }
}


#pragma mark - 公用方法

///灰度邀请提示弹窗
+ (void)presentGreyAlertControllerWithModel:(CAIClientVoModel *)model
                                 configueUI:(nullable CAIUpgradeGeneralUIConfig *)config
                                 greyAction:(void(^)(void))greyResult
{
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"菜划算邀请您参加新版本内测，是否参加？" message:nil preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"取消", @"Cancel") style:UIAlertActionStyleCancel handler:nil];
    [alertController addAction:cancelAction];
    UIAlertAction *doAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"确定", @"OK") style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        if ([NSString caiUpgradeIsEmpty:model.middleUrl]) {
            
            NSString *grayUrl = model.testFlightUrl;
            [CAIUpgradeManager openURLWithUrlString:grayUrl];
        }else{
            if (greyResult) {
                greyResult();
            }
        }
        
    }];
    [alertController addAction:doAction];
    [[CAIUpgradeTool currentViewControllerWithCheckPresented:config.checkCurrentViewPresented] presentViewController:alertController animated:YES completion:nil];
}

+ (void)showGreyAlertWithModel:(CAIClientVoModel *)model
                    configueUI:(nullable CAIUpgradeGeneralUIConfig *)config
                    greyAction:(void(^)(void))greyResult
{
    NSString *title = @"新版本内测邀请";
    UIImage *image =  [CAIUpgradeTool bundleImageNamed:@"grey_img_icon"];
    CAIUpgradeAlert *alert = [CAIUpgradeAlert showAlertWithImage:image
                                                           title:title
                                                         content:model.updateDescription
                                                         isForce:NO
                                                       nextBlock:^{
        if ([NSString caiUpgradeIsEmpty:model.middleUrl]) {
            NSString *grayUrl = model.testFlightUrl;
            [CAIUpgradeManager openURLWithUrlString:grayUrl];
        }else{
            if (greyResult) {
                greyResult();
            }
        }
    }];
    if (config) {
        alert.alertConfig = [self setAlertConfiguration:config];
    }
}

+ (CAIUpdateAlertConfiguration *)setAlertConfiguration:(CAIUpgradeGeneralUIConfig *)config{
    
    CAIUpdateAlertConfiguration *alertCf = [[CAIUpdateAlertConfiguration alloc]init];
    alertCf.doButtonTitle = config.doButtonTitle;
    alertCf.doButtonBackgroundImage = config.doButtonBackgroundImage;
    alertCf.doButtonBackgroundColor = config.doButtonBackgroundColor;
    alertCf.doButtonCornerType = config.doButtonCornerType;
    alertCf.doButtonCornerRadius = config.doButtonCornerRadius;
    alertCf.iconImage = config.grayIconImage;
    return alertCf;
}

//检查是否有新版本
+ (BOOL)isHaveNewVersionWithVersionCompare:(NSString *)itunesVersion
{
    if ([NSString caiUpgradeIsEmpty:itunesVersion]) {
        return NO;
    }
    NSString *currentVersion =  [[NSBundle mainBundle]objectForInfoDictionaryKey:@"CFBundleShortVersionString"];
    if ([itunesVersion compare:currentVersion options:NSNumericSearch] ==NSOrderedDescending)
    {
        return YES;
    }
    return NO;
}

+ (NSString *)appStoreAppInfomationURLForApplicationIdentifier:(NSString *)appId
{
    NSString *lookup = [NSString stringWithFormat:@"http://itunes.apple.com/cn/lookup?id=%@",appId];
    return lookup;
}

+ (NSString *)downLoadUrlWithAppId:(NSString *)appId{
    
    return [NSString stringWithFormat:@"%@%@",@"https://itunes.apple.com/us/app/id",appId];
}


+ (void)openURLToAppStoreForAppStoreUrl:(NSString *)urlString
{
    [self openURLWithUrlString:urlString];
}

+ (void)openURLWithUrlString:(NSString *)urlString
{
    NSURL *url =[NSURL URLWithString:urlString];
    if ([[UIApplication sharedApplication] canOpenURL:url])
    {
        if (@available(iOS 10.0,*)) {
            
            [[UIApplication sharedApplication]openURL:url options:@{} completionHandler:nil];
        }
    }
}

/// isABM的时候，用runtime方式路由跳转
+ (id)chsRouter{
    Class cls = objc_getClass("CHSRouter");
    id (*umSocialManager_msgSend)(id,SEL) = (id (*)(id,SEL))objc_msgSend;
    id umSocialManager = umSocialManager_msgSend(cls,sel_registerName("singletonInstance"));
    return umSocialManager;
}


+ (NSString *)version
{
    return [NSString stringWithFormat:@"1.5.2"];
}

#pragma mark - animation

@end
